<?php

namespace App\Services;

use App\Models\BookIsbn;
use App\Models\Cart;
use App\Models\Goods;
use App\Models\ShopSellRank;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;

/**
 *
 */
class GoodService
{

    /**
     * good appearance group.
     *
     * @Author   wangwenfan
     * @DateTime 2019-11-06
     * @return   array
     */
    public static function appearance()
    {
        return Goods::selectRaw("pinxiang,count(pinxiang) as num")
            ->groupBy('pinxiang')->get()->toArray();
    }

    /**
     * Shop sales ranking
     *
     * @Author   wangwenfan
     * @DateTime 2019-11-09
     *
     * @param int $start_price
     * @param int $end_price
     *
     * @return   Collection
     */
    public static function shopRank($start_price, $end_price)
    {
        $sellNumber = Goods::selectRaw("shop_id,count(shop_id) as sell_number")
            ->whereBetween('price', [$start_price, $end_price])
            ->groupBy('shop_id')->orderBy('sell_number', "desc")->get();
        return $sellNumber;
    }

    public static function addGoods($data = [])
    {
        return Goods::insert($data);
    }

    public static function updateGoods($data = [])
    {
        return Goods::where('item_id', $data['item_id'])->update($data);
    }

    /**
     *
     * @Author   wangwenfan
     * @DateTime 2019-11-09
     *
     * @param array $data
     * @param array $price
     *
     * @return   void
     */
    public static function insertShopRank($data, $price)
    {
        foreach ($data as $value) {
            $shopData = [
                'shop_id'     => $value->shop_id,
                'price_range' => join('-', array_values($price)),
                'sell_number' => $value->sell_number,
            ];
            ShopSellRank::insert($shopData);
        }
    }

    public static function goodSellNumber($item_id, $title)
    {
        $key    = 'sell_' . $item_id;
        $number = Cache::get($key);
        if ($number) {
            return $number;
        } else {
            $number = Goods::where('title', 'like', "%{$title}%")->get()->count();
            Cache::forever($key, $number);
            return $number;
        }
    }

    /**
     * 获取有isbn的商品
     *
     * @Author   wangwenfan
     * @DateTime 2019-12-04
     * @return   [type]     [description]
     */
    public static function isbnGoods($date = '')
    {
        $model = Goods::selectRaw("id,item_id,title,isbn,remark")->where('isbn', '!=', '');
        if ($date) {
            $model->where('created_at', '>', $date);
        }
        return $model->groupBy('isbn')->get();
    }

    /**
     * 根据标题模糊搜索商品
     *
     * @Author   wangwenfan
     * @DateTime 2019-12-04
     *
     * @param    [type]     $title [description]
     *
     * @return   [type]            [description]
     */
    public static function findGood($title)
    {
        return Goods::where('title', 'like', "{$title}%")
            ->where('isbn', '')->where('remark', 0)->get();
    }

    /**
     * 写入isbn表
     *
     * @Author   wangwenfan
     * @DateTime 2019-12-04
     *
     * @param    [type]     $data [description]
     *
     * @return   [type]           [description]
     */
    public static function insertIsbn($data)
    {
        return BookIsbn::insertIgnore($data);
    }

    public static function insertCart($datas)
    {

        $date = Carbon::now()->toDateTimeString();
        foreach ($datas as $data) {
            $hasReserved = $data['item']['hasReserved'];//是否可以锁定和购买
            $lockExpiredTime = $data['item']['lockExpiredTime'] ?? 0;
            $newData = [
                'title' => $data['item']['book']['title'],
                'isbn'    => $data['item']['book']['isbn13'],
                'item_id' => $data['item']['book']['id'],
                'image' => $data['item']['book']['images']['origin'],
                'price' => $data['item']['book']['virtuals']['cartBook']['price'],
                'other_id'=>$data['item']['id'],
                'inStockCount' => $lockExpiredTime,
                'hasReserved' => $hasReserved,
                'created_at' => $date,
                'updated_at' => $date
            ];
            Cart::insertIgnore($newData);
        }
        return true;
    }

    public static function insertDoubanBook($data)
    {
        $price = $data['price'] ?? '';
        if (isset($data['author'])) {
            if (is_array($data['author'])) {
                $author = empty($data['author']) ? '' : $data['author'][0];
            } else {
                $author = $data['author'];
            }
        } else {
            $author = '';
        }

        $created_at = Carbon::now()->toDateTimeString();
        //写入数据库
        $dbData = [
            'isbn10' => $data['isbn10'],
            'isbn13' => $data['isbn13'],
            'title' => $data['title'],
            'author' => $author,
            'pubdate' => $data['pubdate'],
            'publisher' => $data['publisher'],
            'image' => $data['image'],
            'binding' => $data['binding'],
            'pages' => $data['pages'],
            'douban_url' => $data['alt'],
            'author_intro' => $data['author_intro'] ? $data['author_intro'] : '无',
            'price' => $price,
            'price_name' => $data['price'],
            'created_at' => $created_at,
            'updated_at' => $created_at,
        ];

        Log::info("写入豆瓣数据",$dbData);
        return GoodService::insertIsbn($dbData);
    }

}
